//
//  Utility.m
//  HSEDU
//
//  Created by oceans on 2018/7/13.
//  Copyright © 2018年 xvv. All rights reserved.
//

#import "Utility.h"
#import "TipManager.h"
#import <objc/runtime.h>
#import "AppDelegate.h"
#import "LoginViewController.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation Utility

+ (NSString *)randLetters:(int)num onlyLower:(BOOL)onlyLower {
    
    NSString *string = @"0123456789abcdefghijklmnopqrstuvwxyz";
    
    if (!onlyLower) {
        string = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    
    NSString *result = [[NSMutableString alloc]initWithCapacity:num];
    for (int i = 0; i < num; i++) {
        //获取随机数
        NSInteger index = arc4random() % (string.length-1);
        char tempStr = [string characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    
    return result;
}

+ (NSString *)uuid {
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *uuid = [def objectForKey:@"uuid"];
    if (uuid == nil || uuid.length == 0) {
        uuid = [[NSUUID UUID] UUIDString];
        [def setObject:uuid forKey:@"uuid"];
        [def synchronize];
    }
    return uuid;
}

+ (BOOL)checkMobile:(NSString*)mobile {
    
    if (mobile.length == 0) {
        [TipManager showTip:@"请输入手机号"];
        return NO;
    }
    NSString *regex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    NSPredicate *targetPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([targetPredicate evaluateWithObject:mobile]) {
        return YES;
    }
    [TipManager showTip:@"你输入的手机号不能识别"];
    return NO;
}

+ (BOOL)checkPassword:(NSString *) password {
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
}

+ (void)push:(NSDictionary *)params {
    // 类名
    NSString *class = params[@"class"];
    // 创建对象
    id instance = [[NSClassFromString(class) alloc] init];
    if (!instance) {
        return;
    }
    
    // 给对象的属性赋值
    NSDictionary *properties = params[@"property"];
    [properties enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        // 检测这个对象是否存在该属性
        if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
            // kvc赋值
            [instance setValue:obj forKey:key];
        }
    }];
    
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root].root pushViewController:instance animated:YES];
}

+ (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName {
    unsigned int outCount, i, supOutCount;
    
    // 获取对象的属性列表
    objc_property_t *properties = class_copyPropertyList([instance class], &outCount);
    objc_property_t *supProperties = class_copyPropertyList([instance superclass], &supOutCount);
    
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        // 属性名转字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        
        // 判断属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return true;
        }
    }
    
    for (i = 0; i < supOutCount; i++) {
        objc_property_t property = supProperties[i];
        // 属性名转字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        
        // 判断属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return true;
        }
    }
    
    free(properties);
    
    return false;
}

+ (void)pushViewController:(UIViewController *)controller {
    controller.hidesBottomBarWhenPushed = YES;
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root].root pushViewController:controller animated:YES];
}

+ (void)pushViewController:(UIViewController *)controller animated:(BOOL)animated {
    controller.hidesBottomBarWhenPushed = YES;
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root].root pushViewController:controller animated:animated];
}

+ (void)globalShow:(UIView *)view {
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root].view addSubview:view];
}

+ (void)showLogin {
    
    LoginViewController *navi = [[LoginViewController alloc] init];
    navi.modalPresentationStyle = 0;
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root] presentViewController:navi animated:YES completion:nil];
}

+ (NSString *)weekday {
    
    NSDate *date = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *weekdayComponents =
    [gregorian components:NSCalendarUnitWeekday fromDate:date];
    NSInteger _weekday = [weekdayComponents weekday];
    NSString *weekStr;
    if (_weekday == 1) {
        weekStr = @"星期天";
    }else if (_weekday == 2){
        weekStr = @"星期一";
    }else if (_weekday == 3){
        weekStr = @"星期二";
    }else if (_weekday == 4){
        weekStr = @"星期三";
    }else if (_weekday == 5){
        weekStr = @"星期四";
    }else if (_weekday == 6){
        weekStr = @"星期五";
    }else if (_weekday == 7){
        weekStr = @"星期六";
    }
    return weekStr;
}

+ (NSString *)md5:(NSString *)string {
    
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}

@end
